// main.js
// Create a class for the element
class Square extends HTMLElement {
    // Specify observed attributes so that
    // attributeChangedCallback will work
// 触发 attributeChangedCallback()回调函数,必须监听这个属性
    constructor() {
        // Always call super first in constructor
        super();

        const shadow = this.attachShadow({mode: 'open'});

        const div = document.createElement('div');
        const style = document.createElement('style');
        shadow.appendChild(style);
        shadow.appendChild(div);
    }

// 通过定义observedAttributes() get函数来实现，observedAttributes()函数体内包含一个 return语句，返回一个数组，包含了需要监听的属性名称
    static get observedAttributes() {
        return ['c', 'l'];
    }

    // 当 custom element首次被插入文档DOM时，被调用。
    connectedCallback() {
        console.log('Custom square element added to page.');
        updateStyle(this);
    }

// 当 custom element从文档DOM中删除时，被调用。
    disconnectedCallback() {
        console.log('Custom square element removed from page.');
    }

// 当 custom element被移动到新的文档时，被调用。
    adoptedCallback() {
        console.log('Custom square element moved to new page.');
    }

// 当 custom element增加、删除、修改自身属性时，被调用。
    attributeChangedCallback(name, oldValue, newValue) {
        console.log('Custom square element attributes changed.');
        updateStyle(this);
    }
}

customElements.define('custom-square', Square);

function updateStyle(elem) {
    const shadow = elem.shadowRoot;
    const childNodes = Array.from(shadow.childNodes);

    childNodes.forEach(childNode => {
        if (childNode.nodeName === 'STYLE') {
            childNode.textContent = `
        div {
          width: ${elem.getAttribute('l')}px;
          height: ${elem.getAttribute('l')}px;
          background-color: ${elem.getAttribute('c')};
        }
      `;
        }
    });
}

const add = document.querySelector('.add');
const update = document.querySelector('.update');
const remove = document.querySelector('.remove');
let square;

update.disabled = true;
remove.disabled = true;

function random(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

add.onclick = function () {
    // Create a custom square element
    square = document.createElement('custom-square');
    square.setAttribute('l', '100');
    square.setAttribute('c', 'red');
    document.body.appendChild(square);

    update.disabled = false;
    remove.disabled = false;
    add.disabled = true;
};

update.onclick = function () {
    // Randomly update square's attributes
    square.setAttribute('l', random(50, 200));
    square.setAttribute('c', `rgb(${random(0, 255)}, ${random(0, 255)}, ${random(0, 255)})`);
};

remove.onclick = function () {
    // Remove the square
    document.body.removeChild(square);

    update.disabled = true;
    remove.disabled = true;
    add.disabled = false;
};